from django.shortcuts import render

# Create your views here.

import urllib
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from lxml import etree
import requests

import redis
import pymysql




# 百度百科
@csrf_exempt
def baike(request, param):
    # pymysql.connect("192.168.174.140", "root", "root123123", "brinkidea")
    pool = redis.ConnectionPool(host='192.168.174.137', port=6379, decode_responses=True)
    r = redis.Redis(connection_pool=pool)
    result = r.hget("baike", param)
    # 记录搜索次数
    r.hincrby("baike_count", param, 1)
    # 缓存穿透
    if result is None:
        url = "https://baike.baidu.com/item/" + urllib.parse.quote(param)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36"
        }
        req = urllib.request.Request(url=url, headers=headers, method="GET")
        reponse = urllib.request.urlopen(req)
        text = reponse.read().decode("utf-8")
        html = etree.HTML(text)
        sen_list = html.xpath('//div[contains(@class,"lemma-summary") or contains(@class,"lemmaWgt-lemmaSummary")]//text()')
        sen_list_after_filter = [item.strip("\n") for item in sen_list]
        # 加入到缓存中
        r.hset("baike", param, "".join(sen_list_after_filter))
        r.close()
        return HttpResponse(sen_list_after_filter)
    else:
        r.close()
        return HttpResponse(result)



# 百度翻译
@csrf_exempt
def translate(request, param):
    pool = redis.ConnectionPool(host='192.168.174.137', port=6379, decode_responses=True)
    r = redis.Redis(connection_pool=pool)
    result = r.hget("translate", param)
    # 记录搜索次数
    r.hincrby("translate_count", param, 1)
    # 缓存穿透
    if result is None:
        url = "https://fanyi.baidu.com/sug"
        dic = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36"
        }
        kw = {"kw": param}
        resp = requests.post(url, headers=dic, data=kw)
        res = resp.json()  # 将返回的响应直接处理成json
        resp.close()
        translate_result = ''
        for val in res["data"]:  # str["data"])中存放又是字典dic
            translate_result += val["v"]+"|"
        # 添加到缓存中
        r.hset("translate", param, translate_result)
        r.close()
        return HttpResponse(translate_result + "")
    else:
        r.close()
        return HttpResponse(result)
